import {Component, OnInit, ViewChild} from '@angular/core';
import {adSystemApiUrl} from '../../../../config/api';
import {HttpService} from '../../../lib/service/http.service';
import {Http, Headers, RequestOptions, RequestOptionsArgs} from '@angular/http';

@Component({
  selector: 'app-coupon-list',
  templateUrl: 'coupon-list.component.html',
  styleUrls: ['coupon-list.component.scss']
})
export class CouponListComponent implements OnInit {

  searchData = '';
  appletList = [];

  totalItems: number;
  itemsPerPage = 12;
  currentPage = 1;

  constructor(private httpService: HttpService) {
  }

  ngOnInit() {
    this.getAppletList(this.searchData, 1);
  }

  // 获取小程序列表
  getAppletList(name: string, page: number) {
    const url = `${adSystemApiUrl}/v2/admin/merchants/platform_merchants_list_get?name=${name}&page=${page}&pageSize=${this.itemsPerPage}`;
    return this.httpService.httpPostAuth(url, {}).subscribe(
      res => {
        this.totalItems = res.data.total;
        this.currentPage = res.data.current_page;
        this.appletList = res.data.data;
      }
    );
  }

  // 重置
  reset() {
    this.searchData = '';
    this.getAppletList(this.searchData, 1);
  }

  // 搜索
  search() {
    this.getAppletList(this.searchData, 1);
  }

  // 修改卡券状态
  changeCouponStatus(key, status) {
    const url = `${adSystemApiUrl}/v2/admin/merchants/platform_merchants_key_status_change_post`;
    const headers = new Headers({'Content-Type': 'application/json'});
    const options = new RequestOptions({headers: headers});
    const body = JSON.stringify({
      merchant_key: key,
      status: status
    });
    return this.httpService.httpPostAuth(url, body, options).subscribe(res => {
      if (res.code === 2000) {
        this.currentPage = 1;
        this.getAppletList(this.searchData, this.currentPage);
      }
    });
  }

  pageChanged(event: any): void {
    window.scrollTo(0, 0);
    this.getAppletList(this.searchData, event.page);
  }
}
